
export class OuterOreCarryRelayTask implements ICreepTask{
  run(creep: Creep): void {

    if(creep.store.getFreeCapacity(RESOURCE_ENERGY) === 0){
      const storage = Game.rooms[creep.memory.bornRoom].storage;
      if(storage){
        if (creep.transfer(storage, RESOURCE_ENERGY) === ERR_NOT_IN_RANGE) {
          creep.go(storage);
        } 
      }
    }
    else {
      if(creep.memory.relayTarget){
        const relayCreep = Game.getObjectById(creep.memory.relayTarget);
        if(relayCreep){
          if(!relayCreep.memory.relayTarget || (relayCreep.memory.relayTarget && relayCreep.memory.relayTarget !== creep.id)){
            relayCreep.memory.relayTarget = creep.id;
          }
          if(relayCreep.memory.source){
            this.moveToNearestExit(creep,relayCreep.memory.source.pos.roomName);
          }
        }
        else {
          delete creep.memory.relayTarget;
          delete creep.memory.relayExitPos;
        }
      }
    }
  }

  private moveToNearestExit(creep:Creep,targetRoom:string) {
    let exitPos:RoomPosition | null = null;
    if(creep.memory.relayExitPos){
      exitPos = creep.memory.relayExitPos;
    }
    else {
      const exitDir = creep.room.findExitTo(targetRoom) as FindConstant; // 找到距离creep最近的出口方向
      exitPos = creep.pos.findClosestByPath(exitDir); // 找到最近的出口位置
      if(exitPos){
        creep.memory.relayExitPos = exitPos;
      }
    }

    if(exitPos){
      let pos = new RoomPosition(exitPos.x,exitPos.y,exitPos.roomName);
      if(!creep.pos.inRangeTo(pos,2)){
        creep.go(pos);
      }
    }
  }
}